package logging;

import javax.swing.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.LogRecord;
import java.util.logging.StreamHandler;

/**
 * A handler for displaying log records in a window
 */

public class WindowHandler extends StreamHandler {
    private JFrame frame;

    public WindowHandler() {
        final JTextArea output = new JTextArea();
        frame = new JFrame();

        output.setEditable(false);
        frame.setSize(200, 200);
        frame.add(new JScrollPane(output));
        frame.setFocusableWindowState(false);
        frame.setVisible(true);
        setOutputStream(new OutputStream() {
            @Override
            public void write(int i) throws IOException {
            } // not called

            public void write(byte[] b, int off, int len) {
                output.append(new String(b, off, len));
            }
        });
    }

    @Override
    public synchronized void publish(LogRecord logRecord) {
        if (!frame.isVisible()) {
            return;
        }
        super.publish(logRecord);
        flush();
    }
}
